package leetcode

/*
 * @lc app=leetcode.cn id=885 lang=golang
 *
 * [885] 螺旋矩阵 III
 */

// @lc code=start
func spiralMatrixIII(R int, C int, r0 int, c0 int) [][]int {
	n := R * C
	ret := make([][]int, n)
	for i := range ret {
		ret[i] = make([]int, 2)
	}

	i := 1
	appendArr := func(r, c int) bool {
		if 0 <= r && r < R && 0 <= c && c < C {
			ret[i] = []int{r, c}
			i++
		}
		return i >= n
	}

	ret[0] = []int{r0, c0}
	r, c := r0, c0
finish:
	for n := 3; ; n += 2 {
		c++
		flag := appendArr(r, c)
		if flag {
			break
		}
		for r < r0+n/2 {
			r++
			flag = appendArr(r, c)
			if flag {
				break finish
			}
		}
		for c0-n/2 < c {
			c--
			flag = appendArr(r, c)
			if flag {
				break finish
			}
		}
		for r0-n/2 < r {
			r--
			flag = appendArr(r, c)
			if flag {
				break finish
			}
		}
		for c < c0+n/2 {
			c++
			flag = appendArr(r, c)
			if flag {
				break finish
			}
		}
	}

	return ret
}

func spiralMatrixIII2(R int, C int, r0 int, c0 int) [][]int {
	n := R * C
	if n == 1 {
		return [][]int{{0, 0}}
	}
	ret := make([][]int, n)
	for i := range ret {
		ret[i] = make([]int, 2)
	}
	ret[0] = []int{r0, c0}

	r, c, i := r0, c0, 1
	for m := 1; ; m += 2 {
		for _, obj := range [][]int{{0, 1, m}, {1, 0, m}, {0, -1, m + 1}, {-1, 0, m + 1}} {
			dr, dc, k := obj[0], obj[1], obj[2]
			for j := 0; j < k; j++ {
				r += dr
				c += dc
				if 0 <= r && r < R && 0 <= c && c < C {
					ret[i] = []int{r, c}
					i++
					if i >= n {
						return ret
					}
				}
			}
		}
	}
}

// @lc code=end
